package cn.stylefeng.guns.modular.gridsystem.hechuang;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.gridsystem.websocket.Message;
import com.google.gson.Gson;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/*import net.aivoicetech.compose.http.GsonUtils;
import net.aivoicetech.controller.AccelerationOnOrOffController;
import net.aivoicetech.entity.AccelerationOnOrOff;
import net.aivoicetech.iaudio.conf.OpticalFiberConfiguration;
import net.aivoicetech.iaudio.conf.TcpConfiguration;
import net.aivoicetech.iaudio.conf.WebConfiguration;
import net.aivoicetech.iaudio.entity.Message;
import net.aivoicetech.iaudio.entity.MessageInspection;
import net.aivoicetech.iaudio.entity.MessageStart;
import net.aivoicetech.iaudio.entity.OpticalChannelInformation;
import net.aivoicetech.iaudio.intf.AbstractCollector;
import net.aivoicetech.iaudio.utils.OpticalHttp;*/
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.*;

@Configuration
@Slf4j
@Data
public class TestScoket implements Runnable {

    public static volatile String fromData;

    public static volatile String toData;

    public static volatile String featureType;

    private WebSocketClient mWsClient;

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

    private ScheduledFuture<?> heartBeatFuture;

    private ScheduledFuture<?> recoveryFuture;

    private ExecutorService executorServiceWsClient = Executors.newFixedThreadPool(1);

    private Future<?> future;




/*    public WebSocketClientFactory() {

        future = executorServiceWsClient.submit(() -> {
            // 异步操作的代码块
            this.mWsClient = createWsClient("1555");
        });

    }*/

    /**
     * 心跳机制
     * 当ws连接后，启动心跳，异常时停止心跳包
     */
    private class HeartBeat implements Runnable {

        @Override
        public void run() {
            if (mWsClient != null && mWsClient.isOpen()) {
                mWsClient.send("");
            }
        }
    }

    /**
     * 断线重连机制
     * 当服务断连时启动，不断重试，直到连接成功时停止
     */
    private class WsRecovery implements Runnable {

        @Override
        public void run() {
            log.info("正在尝试恢复");
            if (mWsClient != null && mWsClient.isOpen()) {
                return;
            }

            log.info("正在开始恢复");
            mWsClient = createWsClient("1555");
        }
    }

    private WebSocketClient createWsClient(String encode) {
        // log.info("地址:" + tcpConfiguration.getIp() + ":" + tcpConfiguration.getPort() + "/ws/gateway/" + webConfiguration.getDeviceNum());
        // String url = "ws://" + tcpConfiguration.getIp() + ":" + tcpConfiguration.getPort() + "/ws/gateway/" + webConfiguration.getDeviceNum();
        final WebSocketClient webSocketClient = new WebSocketClient(URI.create("url")) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                log.info(serverHandshake.getHttpStatus() + "open");
                log.info("启动心跳");
                //启动心跳线程
                startHeartBeat();
                //结束故障恢复线程
                stopRecoveryTask();
            }

            @Override
            public void onMessage(String s) {

            }

            @Override
            public void onClose(int i, String s, boolean b) {
                log.info("close  i: " + i + " s :" + s + " b :" + b);
                //结束心跳包
                stopHeartBeatTask();
                //启动故障恢复
                startRecoveryTask();
            }

            @Override
            public void onError(Exception e) {
                log.info("error;" + e.getLocalizedMessage());
                //结束心跳包
                stopHeartBeatTask();

                //启动故障恢复
                startRecoveryTask();
            }
        };
        try {
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            log.error("#connectBlocking: " + e.getMessage());
            return null;
        }
    }

    public void sendMsg(String message) {
        if (mWsClient != null && mWsClient.isOpen()) {
            mWsClient.send(message);
        }
    }

    private void startHeartBeat() {
        if (heartBeatFuture == null || heartBeatFuture.isCancelled()) {
            heartBeatFuture = executorService.scheduleAtFixedRate(new HeartBeat(), 1, 10, TimeUnit.SECONDS);
        }
    }

    private void stopRecoveryTask() {
        if (recoveryFuture != null && !recoveryFuture.isCancelled()) {
            recoveryFuture.cancel(false);
            recoveryFuture = null;
            log.info("结束故障恢复线程");
        }
    }

    private void startRecoveryTask() {
        if (recoveryFuture == null || recoveryFuture.isCancelled()) {
            future.cancel(true);
            executorServiceWsClient.isShutdown();
            recoveryFuture = executorService.scheduleAtFixedRate(new WsRecovery(), 1, 10, TimeUnit.SECONDS);
            log.info("启动故障恢复");
        }
    }

    private void stopHeartBeatTask() {
        if (heartBeatFuture != null && !heartBeatFuture.isCancelled()) {
            log.info("结束心跳");
            heartBeatFuture.cancel(false);
            heartBeatFuture = null;
        }
    }

    @Override
    public void run() {
        log.info("启动WebSocketClientFactory");
    }
}
